package com.ch.learning.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.redis.util.RedisLockRegistry;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * @Description
 * @Author cj-chenhao on 2020-01-17 15:42
 */
@RequestMapping(value = "/redis")
@RestController
@Slf4j
public class RedisLockController {
    @Autowired
    private RedisLockRegistry redisLockRegistry;


    @RequestMapping(value = "/lock")
    public String lock(){
        String result = "";
        final Lock lock = redisLockRegistry.obtain("h");
        try {
            final String threadName = Thread.currentThread().getName();
            if(lock.tryLock(2, TimeUnit.SECONDS)){
                try {
                    result = threadName + "获取锁成功";
                    // TimeUnit.SECONDS.sleep(10);
                }finally {
                    // lock.unlock();
                }
            }else {
                result = threadName + "获取锁失败";
            }
            log.info("{}", result);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return result;
    }
}
